package com.mingqijia.gassafety.console.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.base.CommonResponse;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.db.entity.FieldTemplate;
import com.mingqijia.gassafety.db.entity.auth.BaseEntry;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.mapper.FieldTemplateMapper;
import com.mingqijia.gassafety.shared.constant.ExportCodeEnum;
import com.mingqijia.gassafety.shared.constant.ExportListCode;
import com.mingqijia.gassafety.shared.constant.UploadCodeEnum;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.FileExportCreateRequest;
import com.mingqijia.gassafety.webserver.request.FileExportQueryRequest;
import com.mingqijia.gassafety.webserver.request.FileUploadQueryRequest;
import com.mingqijia.gassafety.webserver.response.FieldListShowResponse;
import com.mingqijia.gassafety.webserver.response.FileExportResponse;
import com.mingqijia.gassafety.webserver.response.FileUploadResponse;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import com.mingqijia.gassafety.webserver.service.FieldListShowService;
import com.mingqijia.gassafety.webserver.service.FileExportService;
import com.mingqijia.gassafety.webserver.service.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.Year;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 异步导出
 *
 * @author wanghai
 * @since 2022-02-21
 */


@Slf4j
@RestController
@RequestMapping("/business/v1/shared/file")
@Api(tags = "异步导出")
public class FileController {

    @Autowired
    FileExportService fileExportService;

    @Autowired
    FileUploadService fileUploadService;
    @Autowired
    FieldListShowService fieldListShowService;
    @Autowired
    FieldTemplateMapper fieldTemplateMapper;
    @Autowired
    CompanyService companyService;

    @ApiOperation(value = "任务创建")
    @PostMapping(value = "/export/create")
    public CommonResponse<Object> createExport(@RequestBody @Valid FileExportCreateRequest request){
        String spId = ApplicationUtils.getWorkingSpId();
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        if (request.getQueryBody().get("authority") != null && "service".equals(request.getQueryBody().get("authority").toString())) {
            template.setTemplateType(3);
        }
        if (request.getExportCode().equals("EXPORT0016")) {
            if ("year".equals(request.getQueryBody().get("cateory").toString())) {
                template.setTemplateType(5);
            } else {
                String stateDay = request.getQueryBody().get("stateDay").toString();
                String[] months = stateDay.split("-");
                if (months.length == 2) {
                    if ("02".equals(months[1])) {
                        int currentYear = Year.now().getValue();
                        if (isLeapYear(currentYear)) {
                            template.setTemplateType(3);
                        } else {
                            template.setTemplateType(4);
                        }
                    } else if ("04".equals(months[1]) || "06".equals(months[1]) || "09".equals(months[1]) || "11".equals(months[1])) {
                        template.setTemplateType(2);
                    }
                }
            }
        }
        ExportCodeEnum exportCodeEnum = ExportCodeEnum.getExportCode(request.getExportCode(), template.getTemplateType());
//        后面动态字段导出使用
        if (template.getTemplateType() == 1 && !StringUtils.isEmpty(ExportListCode.parse(exportCodeEnum.getCode()).getValue())) {
            List<FieldListShowResponse> responses = fieldListShowService.queryListShow(ExportListCode.parse(exportCodeEnum.getCode()).getValue(), spId);
            List<String> fields = responses.stream().map(FieldListShowResponse::getFieldCode).collect(Collectors.toList());
            List<String> titles = responses.stream().map(FieldListShowResponse::getFieldName).collect(Collectors.toList());
            exportCodeEnum = ExportCodeEnum.updateExport(exportCodeEnum,fields.toArray(new String[]{}),titles.toArray(new String[]{}));
        }
        if (exportCodeEnum == null) {
            throw new BizException("数据表种类代号不存在");
        }
        fileExportService.create(request ,template);
        return CommonResponse.success( "success" );

    }

    /**
     * 查询导出任务
     * @param request
     * @return
     */
    @ApiOperation(value = "导出任务列表")
    @PostMapping(value = "/export/list")
    public CommonResponse<PageUtil<FileExportResponse>> getExportList(@RequestBody @Valid FileExportQueryRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        ExportCodeEnum exportCodeEnum = ExportCodeEnum.getExportCode(request.getExportCode(), template.getTemplateType());
        if (exportCodeEnum == null) {
            throw new BizException("数据表种类代号不存在");
        }
        return CommonResponse.success(fileExportService.getList(request),"success");
    }

    /**
     * 查询导出任务
     * @param request
     * @return
     */
    @ApiOperation(value = "导出任务列表")
    @PostMapping(value = "/export/pdfList")
    public CommonResponse<PageUtil<FileExportResponse>> getExportPdfList(@RequestBody @Valid FileExportQueryRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        ExportCodeEnum exportCodeEnum = ExportCodeEnum.getExportCode(request.getExportCode(), template.getTemplateType());
        if (exportCodeEnum == null) {
            throw new BizException("数据表种类代号不存在");
        }
        return CommonResponse.success(fileExportService.getPdfList(request),"success");
    }

    @ApiOperation(value = "导入任务列表")
    @PostMapping(value = "/upload/list")
    public CommonResponse<PageUtil<FileUploadResponse>> getUploadList(@RequestBody @Valid FileUploadQueryRequest request){
        UploadCodeEnum uploadCodeEnum = UploadCodeEnum.getUploadCode( request.getUploadCode() );
        if (uploadCodeEnum == null) {
            throw new BizException("数据表种类代号不存在");
        }
        return CommonResponse.success( fileUploadService.getUploadList(request) );
    }

    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
}
